package com.zsr.servlet;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * servlet 核心方法
 */
public class HelloServlet implements Servlet {


    public HelloServlet() {
        System.out.println("1.构造方法");
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("2.初始化方法");

        //ServletConfig的作用
        //        1.可以获取Servlet程序的别名servlet-name的值
        //​	servletConfig.getServletName();
        System.out.println("Servlet的别名是："+servletConfig.getServletName());
        //        2.可以初始化参数init-param
        System.out.println("初始化参数username的值是："+servletConfig.getInitParameter("username"));
        //        3.获取ServletContext对象
        System.out.println(servletConfig.getServletContext());
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    /**
     * service方法是专门用来处理请求和响应的
     * @param servletRequest
     * @param servletResponse
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("3.Hello Servlet 被访问了");
        //类型转换 （因为它有getMethod()方法）
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        //获取请求的方式
        String method =httpServletRequest.getMethod();

//        System.out.println(method);
        if("GET".equals(method)){
            System.out.println("GET请求");
        }else if("POST".equals(method)){
            System.out.println("POST请求");
        }
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {
        System.out.println("4. destroy 销毁");
    }
}
